package com.msa.msaportal.controller;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.msa.msaportal.common.page.Pagination;
import com.msa.msaportal.common.web.JavaTimeUtils;
import com.msa.msaportal.common.web.MsaJsonUntil;
import com.msa.msaportal.common.web.ResponseUtils;
import com.msa.msaportal.entity.PortalExample;
import com.msa.msaportal.entity.PortalFunction;
import com.msa.msaportal.entity.PortalPage;
import com.msa.msaportal.entity.PortalRole;
import com.msa.msaportal.entity.PortletEntity;
import com.msa.msaportal.service.IPortalExampleService;
import com.msa.msaportal.service.IPortalPageService;
import com.msa.msaportal.service.IPortalRoleService;

@Controller
@RequestMapping("/Portalrole")  
public class PortalRoleController {

	@Resource(name="roleManager")
	private IPortalRoleService roleManager;
	@Resource(name="portalManager")
	private IPortalExampleService portalManager;
	@Resource(name="pageManager")
	private IPortalPageService pageManager;
	/**
	 * 保存角色
	 * @param bean
	 * @param permfs
	 * @param permps
	 * @param permgs
	 * @param permts
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveRole.do")
	public void saveRole(PortalRole bean,String permfs,String permps,String permgs,String permts,
			HttpServletRequest request,HttpServletResponse response){

		//处理角色-功能项
		Set<PortalFunction> hst = new HashSet<PortalFunction>();
		if(!permfs.equals("") && permfs.indexOf(",")!=-1){
			String[] str = permfs.split(",");
			for(int i=0;i<str.length;i++){
				PortalFunction portalFunction = roleManager.findByid(Integer.valueOf(str[i]));
				hst.add(portalFunction);
			}
		}else if(!permfs.equals("") && permfs.indexOf(",")==-1){
			PortalFunction portalFunction = roleManager.findByid(Integer.valueOf(permfs));
			hst.add(portalFunction);
		}
		//角色-实例
		Set<PortalExample> spe = new HashSet<PortalExample>();
		if(!permps.equals("") && permps.indexOf(",")!=-1){
			String[] pid = permps.split(",");
			for(int i=0;i<pid.length;i++){
				PortalExample portalExample = portalManager.findByPortalid(pid[i]);
				spe.add(portalExample);
			}
		}else if(!permps.equals("") && permps.indexOf(",")==-1){
			PortalExample portalExample = portalManager.findByPortalid(permps);
			spe.add(portalExample);
		}
		//角色-页
		Set<PortalPage> spg = new HashSet<PortalPage>();
		if(!permgs.equals("") && permgs.indexOf(",")!=-1){
			String[] pageid = permgs.split(",");
			for(int i=0;i<pageid.length;i++){
				PortalPage portalPage = pageManager.findById(Integer.valueOf(pageid[i]));
				spg.add(portalPage);
			}
		}else if(!permgs.equals("") && permgs.indexOf(",")==-1){
			PortalPage portalPage = pageManager.findById(Integer.valueOf(permgs));
			spg.add(portalPage);
		}
		//角色-portlet
		Set<PortletEntity> spt = new HashSet<PortletEntity>();
		if(!permts.equals("") && permts.indexOf(",")!=-1){
			String[] portletid = permts.split(",");
			for(int i=0;i<portletid.length;i++){
				PortletEntity portletEntity = pageManager.findPortletById(Integer.valueOf(portletid[i]));
				spt.add(portletEntity);
			}
		}else if(!permts.equals("") && permts.indexOf(",")==-1){
			PortletEntity portletEntity = pageManager.findPortletById(Integer.valueOf(permts));
			spt.add(portletEntity);
		}
		bean.setPortalFunction(hst);
		bean.setPortalExample(spe);
		bean.setPortalPage(spg);
		bean.setPortletEntity(spt);
		bean.setCreatetime(JavaTimeUtils.getCurrentTime());
		roleManager.saveRole(bean);
		ResponseUtils.renderText(response, "保存成功！");
	}
	/**
	 * 角色编辑
	 * @param roleid
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/editRole.do")
	public void eidtRole(Integer roleid,HttpServletRequest request,HttpServletResponse response){
		
		PortalRole portalrole = roleManager.findById(roleid);
		//获取功能
		Set<PortalFunction> portalfunctions = portalrole.getPortalFunction();
		//获取关联
		Set<PortletEntity> portlet = portalrole.getPortletEntity();
		
		JSONObject json = new JSONObject();
		json.put("roleid", portalrole.getRole_id());
		json.put("rolename", portalrole.getRole_name());
		json.put("roleorder", portalrole.getRole_order());
		json.put("creatime", portalrole.getCreatetime());
		List<String> ltree = new ArrayList<String>();
		String fun="";
		String ptrole="";
		for(Iterator it=portalfunctions.iterator();it.hasNext();){
			PortalFunction  pf = (PortalFunction) it.next();
			fun += pf.getFunctionId()+",";
		}
		List<String> petree = new ArrayList<String>();
		for(Iterator it=portlet.iterator();it.hasNext();){
			PortletEntity pt = (PortletEntity) it.next();
			ptrole += pt.getPortletId()+",";
		}
		if(fun.length()>0){
			fun = fun.substring(0, fun.length()-1);
		}
		
		if(ptrole.length()>0){
			ptrole = ptrole.substring(0, ptrole.length()-1);
		}
			
		ltree.add(fun);
		petree.add(ptrole);
		JSONArray jsarry = JSONArray.fromObject(ltree);
		JSONArray pearry = JSONArray.fromObject(petree);
		json.put("funrole", jsarry);
		json.put("portalrole", pearry);
		ResponseUtils.renderJson(response, json.toString());
	}
	/**
	 * @throws IOException 
	 * 
	 */
	@RequestMapping("/addRole.do")
	public void addRole(HttpServletRequest request,HttpServletResponse response){
		List<PortalFunction> list = roleManager.getfunctionlist();
		String json = "{id:0, pId:0, name:'根目录', open:true}";
		List<String> lstTree = new ArrayList<String>();
		lstTree.add(json);
		for(int i=0;i<list.size();i++){
			if(list.get(i).getFunctionsort().equals("button")){
				String jsonb = "{'id':'"+list.get(i).getFunctionId()+"','pId':'"+list.get(i).getPerent_id()+"','name':'"+list.get(i).getFunctionName()+"','permf':'"+list.get(i).getFunctionId()+"','permb':'"+list.get(i).getFunctionId()+"'}";
				lstTree.add(jsonb);
			}else{
				String jsonp ="{'id':'"+list.get(i).getFunctionId()+"','pId':'"+list.get(i).getPerent_id()+"','name':'"+list.get(i).getFunctionName()+"','permf':'"+list.get(i).getFunctionId()+"'}";
				lstTree.add(jsonp);
			}
			
		}
		
		ResponseUtils.renderJson(response, JSONArray.fromObject(lstTree).toString());
	}
	/**
	 * 获得portlet授权树
	 * @param request
	 * @param response
	 * @throws RemoteException
	 */
	@RequestMapping("/getPortlet.do")
	public void getPortlet(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws RemoteException{
		String userId = (String) session.getAttribute("loginUserId");
		//从ldap获取用户信息
		String udjson = MsaJsonUntil.getJsonByUserId(userId);
		
		JSONObject jobj=JSONObject.fromObject(udjson);
		
		String orgCode = jobj.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getString("organizations");
		String json = "{id:0, pId:0, name:'所有门户实例', open:true}";
		List<String> lstTree = new ArrayList<String>();
		lstTree.add(json);
		List<PortalExample> portallist = portalManager.getPortallistByorgCode(orgCode);
		
		for(int i=0;i<portallist.size();i++){
			String jsonp = "{'id':'"+portallist.get(i).getPortal_id()+"',pId:0,name:'"+portallist.get(i).getPortal_name()+"','permp':'"+portallist.get(i).getPortal_id()+"'}";
			List<PortalPage> pagelist = pageManager.getPageListByPortal(portallist.get(i));
			lstTree.add(jsonp);
			for(int j=0;j<pagelist.size();j++){
				List<PortletEntity> portletlist = pageManager.getPortletlistBypageId(pagelist.get(j).getPageId());
				String jsonl = "{'id':'"+pagelist.get(j).getPageId()+"','pId':'"+pagelist.get(j).getPortalExample().getPortal_id()+"','name':'"+pagelist.get(j).getPageName()+"','permg':'"+pagelist.get(j).getPageId()+"'}";
				lstTree.add(jsonl);
				for(int k=0;k<portletlist.size();k++){
					String jsonk = "{'id':'"+portletlist.get(k).getPortletId()+"','pId':'"+portletlist.get(k).getPortalPage().getPageId()+"','name':'"+portletlist.get(k).getPortletName()+"','permt':'"+portletlist.get(k).getPortletId()+"'}";
					lstTree.add(jsonk);
				}
			}
		}
		ResponseUtils.renderJson(response, JSONArray.fromObject(lstTree).toString());
	}
	/**
	 * 获取角色列表
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/roleManage.do")
	public String getRolelist(String role_name,Integer pageNo,Integer pageSize,ModelMap model,HttpSession session){
		if(pageSize==null){
			pageSize = Pagination.DEF_COUNT;
		}
		Pagination pageModel = roleManager.getRole(role_name, Pagination.cpn(pageNo), pageSize);
		//功能权限控制
		String rolestr = (String) session.getAttribute("productRoleid");
		String [] str = new String[rolestr.split(",").length];
		rolestr = rolestr.substring(0, rolestr.length()-1);
		str = rolestr.split(",");
				
		String role_add = "";
		String role_update = "";
		String role_delete = "";
		for(int j=0;j<str.length;j++){
			PortalRole portalRole = roleManager.findById(Integer.valueOf(str[j]));
			Set<PortalFunction> portalfunction =portalRole.getPortalFunction();
			for(Iterator it=portalfunction.iterator();it.hasNext();){
				PortalFunction  pf = (PortalFunction) it.next();
				if(pf.getFunctionCode().equals("role_new")){
					role_add = pf.getFunctionCode();
				}
				if(pf.getFunctionCode().equals("role_edit")){
					role_update =pf.getFunctionCode();
				}
				if(pf.getFunctionCode().equals("role_remove")){
					role_delete =pf.getFunctionCode();
				}
				
			}
		}
		
		model.addAttribute("nextpage", pageModel.getNextPage());
		model.addAttribute("pageNo", pageModel.getPageNo());
		model.addAttribute("prepage", pageModel.getPrePage());
		model.addAttribute("totalpage", pageModel.getTotalPage());
		model.addAttribute("totalcount", pageModel.getTotalCount());
		model.addAttribute("rolename", role_name);
		model.addAttribute("roleList", pageModel.getList());
		model.addAttribute("role_add", role_add);
		model.addAttribute("role_update", role_update);
		model.addAttribute("role_delete", role_delete);
		return "/sysManage";
	}
	/**
	 * 更新角色
	 * @param bean
	 * @param epermfs
	 * @param epermps
	 * @param epermgs
	 * @param epermts
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updateRole.do")
	public void updateRole(PortalRole bean,String epermfs,String epermps,String epermgs,String epermts,
			HttpServletRequest request,HttpServletResponse response){
		//处理角色-功能项
		Set<PortalFunction> hst = new HashSet<PortalFunction>();
		if(!epermfs.equals("") && epermfs.indexOf(",")!=-1){
			String[] str = epermfs.split(",");
			for(int i=0;i<str.length;i++){
				PortalFunction portalFunction = roleManager.findByid(Integer.valueOf(str[i]));
				hst.add(portalFunction);
			}
		}else if(!epermfs.equals("") && epermfs.indexOf(",")==-1){
			PortalFunction portalFunction = roleManager.findByid(Integer.valueOf(epermfs));
			hst.add(portalFunction);
		}
		//角色-实例
		Set<PortalExample> spe = new HashSet<PortalExample>();
		if(!epermps.equals("") && epermps.indexOf(",")!=-1){
			String[] pid = epermps.split(",");
			for(int i=0;i<pid.length;i++){
				PortalExample portalExample = portalManager.findByPortalid(pid[i]);
				spe.add(portalExample);
			}
		}else if(!epermps.equals("") && epermps.indexOf(",")==-1){
			PortalExample portalExample = portalManager.findByPortalid(epermps);
			spe.add(portalExample);
		}
		//角色-页
		Set<PortalPage> spg = new HashSet<PortalPage>();
		if(!epermgs.equals("") && epermgs.indexOf(",")!=-1){
			String[] pageid = epermgs.split(",");
			for(int i=0;i<pageid.length;i++){
				PortalPage portalPage = pageManager.findById(Integer.valueOf(pageid[i]));
				spg.add(portalPage);
			}
		}else if(!epermgs.equals("") && epermgs.indexOf(",")==-1){
			PortalPage portalPage = pageManager.findById(Integer.valueOf(epermgs));
			spg.add(portalPage);
		}
		//角色-portlet
		Set<PortletEntity> spt = new HashSet<PortletEntity>();
		if(!epermts.equals("") && epermts.indexOf(",")!=-1){
			String[] portletid = epermts.split(",");
			for(int i=0;i<portletid.length;i++){
				PortletEntity portletEntity = pageManager.findPortletById(Integer.valueOf(portletid[i]));
				spt.add(portletEntity);
			}
		}else if(!epermts.equals("") && epermts.indexOf(",")==-1){
			PortletEntity portletEntity = pageManager.findPortletById(Integer.valueOf(epermts));
			spt.add(portletEntity);
		}
		bean.setPortalFunction(hst);
		bean.setPortalExample(spe);
		bean.setPortalPage(spg);
		bean.setPortletEntity(spt);
		bean.setUpdatetime(JavaTimeUtils.getCurrentTime());
		roleManager.updateRole(bean);
		ResponseUtils.renderText(response, "修改成功！");
	}
	/**
	 * 删除角色
	 * @param roleId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/removeRole.do")
	public void deleteRole(Integer roleId,HttpServletRequest request,HttpServletResponse response){
		
		PortalRole portalRole = roleManager.findById(roleId);
		roleManager.deleteRole(portalRole);
		ResponseUtils.renderText(response, "删除成功");
	}
}
